﻿using Padsurface.App.Services.Interfaces;
using Padsurface.App.ViewModels.Start;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using Windows.Storage;

namespace Padsurface.App.Services
{
    [Export(typeof(IRecentSongCache))]
    internal class RecentSongCache : IRecentSongCache
    {
        private const string RecentSongSettingsKey = "RecentSongSettingsKey";
        private const int MaximumRecentSongs = 10;

        private List<string> RecentSongFilePaths
        {
            get
            {
                var recentSongFilePaths = (ApplicationData.Current.LocalSettings.Values[RecentSongSettingsKey] as List<string>);

                if (recentSongFilePaths == null)
                {
                    recentSongFilePaths = new List<string>();
                    ApplicationData.Current.LocalSettings.Values[RecentSongSettingsKey] = recentSongFilePaths;
                }

                return recentSongFilePaths;
            }
        }

        public void Add(StorageFile songFile)
        {
            if (songFile == null) throw new ArgumentNullException("songFile");
            if (string.IsNullOrWhiteSpace(songFile.Path)) throw new ArgumentException("Path is empty", "songFile");

            RecentSongFilePaths.Insert(0, songFile.Path);

            while (RecentSongFilePaths.Count >= MaximumRecentSongs)
                RecentSongFilePaths.Remove(RecentSongFilePaths.Last());
        }

        public IEnumerable<SongProjectViewModel> Load()
        {
            return RecentSongFilePaths.Select(s => new SongProjectViewModel(s));
        }
    }
}
